import React, { useState, useEffect } from 'react';
import SearchBar from './components/SearchBar';
import SearchResults from './components/SearchResults';
import LoadingSpinner from './components/LoadingSpinner';
import { SoftwareResult } from '../shared/preload';

function App() {
  const [searchResults, setSearchResults] = useState<SoftwareResult[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [searchHistory, setSearchHistory] = useState<string[]>([]);

  useEffect(() => {
    loadSearchHistory();
  }, []);

  const loadSearchHistory = async () => {
    try {
      const history = await window.electronAPI.getSearchHistory();
      setSearchHistory(history);
    } catch (error) {
      console.error('Failed to load search history:', error);
    }
  };

  const handleSearch = async (keyword: string) => {
    if (!keyword.trim()) {
      setSearchResults([]);
      return;
    }

    setIsLoading(true);
    try {
      const results = await window.electronAPI.searchSoftware(keyword);
      setSearchResults(results);
      loadSearchHistory();
    } catch (error) {
      console.error('Search failed:', error);
      setSearchResults([]);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-gray-50">
      <header className="bg-white border-b border-gray-200">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center">
              <div className="flex-shrink-0">
                <h1 className="text-2xl font-bold text-primary-600">CleanFinder</h1>
              </div>
              <div className="ml-4 text-sm text-gray-500">
                无广告 · AI智能软件发现
              </div>
            </div>
          </div>
        </div>
      </header>

      <main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="text-center mb-8">
          <h2 className="text-3xl font-bold text-gray-900 mb-4">
            发现最适合你的软件
          </h2>
          <p className="text-lg text-gray-600 max-w-2xl mx-auto">
            输入关键词，让AI为你推荐最匹配的软件及其官方网站
          </p>
        </div>

        <SearchBar onSearch={handleSearch} searchHistory={searchHistory} />
        
        {isLoading && <LoadingSpinner />}
        
        <SearchResults results={searchResults} />
      </main>

      <footer className="bg-white border-t border-gray-200 mt-16">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="text-center text-sm text-gray-500">
            © 2024 CleanFinder Browser. 纯净无广告体验。
          </div>
        </div>
      </footer>
    </div>
  );
}

export default App;
